package com.spbdx.framework.config;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * Description TODO
 *
 * @author chenwei
 * @version 1.0
 * @date 2023/8/25 15:52
 */
@Component
public class KeyStringRedisSerializer implements RedisSerializer<String> {

    private String cachePrefix;

    @Autowired
    private Environment env;

    @Override
    public String deserialize(@Nullable byte[] bytes) {
        return (bytes == null ? null : new String(bytes, StandardCharsets.UTF_8).replaceFirst(getPrefix(), ""));
    }

    @Override
    public byte[] serialize(@Nullable String string) {
        return (string == null ? null : (getPrefix() + string).getBytes(StandardCharsets.UTF_8));
    }

    private String getPrefix() {
        if (StringUtils.isEmpty(cachePrefix)) {
            synchronized (KeyStringRedisSerializer.class) {
                if (StringUtils.isEmpty(cachePrefix)) {
                    String applicationName = env.getProperty("spring.application.name");
                    if (StringUtils.isEmpty(applicationName)) {
                        String url = env.getProperty("spring.datasource.druid.master.url");
                        cachePrefix = StringUtils.substring(url, StringUtils.lastIndexOf(url, "/") + 1, StringUtils.lastIndexOf(url, "?"));
                    } else {
                        cachePrefix = applicationName;
                    }
                    cachePrefix = cachePrefix + ":";
                }
            }
        }
        return cachePrefix;
    }

    public static void main(String[] args) {
        String s = "jdbc:mysql://127.0.0.1:3306/disabilities?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8";
        System.out.println(StringUtils.substring(s, StringUtils.lastIndexOf(s, "/") + 1, StringUtils.lastIndexOf(s, "?")));
    }
}